from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.conf import settings
import os
from alipay import AliPay


from meiduo_mall.utils.views import LoginRequiredJSONMixin
from orders.models import OrderInfo, OrderGoods
from . models import Payment
# Create your views here.


class PaymentView(LoginRequiredJSONMixin, View):
    """订单支付功能,点‘去支付’时调用"""
    def get(self, request, order_id):

        # 1.提取参数(路径参数，不用提取)
        user = request.user
        # 2.校验参数
        try:
            OrderInfo.objects.get(pk=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist as e:
            return JsonResponse({'code': 400, 'errmsg': '订单不存在'})

        # 3.业务数据处理
        # 3.1创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID, # 支付宝给的应用ID
            app_notify_url=None,  # 回调地址，需要真实的网址，在这里测试不类
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),
            sign_type='RSA2', # 有默认值
            debug=settings.ALIPAY_DEBUG   # 调试模式，对接沙箱应用时为True,对接正式应用时为False
        )

        # 3.2生成登录支付宝连接
        order = OrderInfo.objects.get(pk=order_id)
        alipay_string = alipay.api_alipay_trade_page_pay(
            subject='美多商城%s'%order_id,
            out_trade_no=order_id,
            total_amount=float(order.total_amount),
            # total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL,
            sign_type='RSA2',  # 有默认值
        )
        alipay_url = settings.ALIPAY_URL + '?' + alipay_string

        # 4.构建响应
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'alipay_url': alipay_url
        })



class PaymentStatusView(LoginRequiredJSONMixin, View):
    """保存订单支付结果"""
    def put(self, request):

        # 1.提取参数
        data = request.GET.dict()
        sign = data.pop('sign')
        # 2.校验参数
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),
            debug = settings.ALIPAY_DEBUG
        )
        # 3.业务数据处理
        order_id = data.get('out_trade_no')
        trade_id = data.get('trade_no')

        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_id
        )

        order = OrderInfo.objects.get(pk=order_id)
        order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        order.save()
        # 4.构建响应
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'trade_id': trade_id
        })






































